package com.zhiyizhen.handheld.component.personal.view;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.zhiyizhen.handheld.common.ScreenUtil;

public class RightAnchorPopupHelper {
    /**
     * 显示一个位于锚点View正上方的PopupWindow
     *
     * @param context     上下文
     * @param anchor      锚点View
     * @param layoutResId PopupWindow的布局资源ID
     * @return 显示的PopupWindow实例
     */
    public static PopupWindow showRightAnchor(Context context, View anchor, int layoutResId) {
        // 加载PopupWindow的布局
        View contentView = LayoutInflater.from(context).inflate(layoutResId, null);

        // 创建PopupWindow
        PopupWindow popupWindow = new PopupWindow(
                contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true // 可点击
        );

        // 计算PopupWindow的位置
        calculateAndShowPopup(popupWindow, anchor, contentView);

        return popupWindow;
    }

    /**
     * 计算并显示PopupWindow在锚点正右方
     */
    private static void calculateAndShowPopup(PopupWindow popupWindow, View anchorView, View contentView) {
        // 测量contentView以获取其宽高
        contentView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
        int popupWidth = contentView.getMeasuredWidth();
        int popupHeight = contentView.getMeasuredHeight();

        int[] anchorLocation = new int[2];
        anchorView.getLocationOnScreen(anchorLocation);
        int anchorX = anchorLocation[0];
        int anchorY = anchorLocation[1];
        int anchorWidth = anchorView.getWidth(); // 锚点View的宽度

// 4. 显示PopupWindow在锚点正右方
        popupWindow.showAtLocation(
                anchorView,  // 参照View
                Gravity.NO_GRAVITY,  // 不使用系统重力，手动定位
                anchorX + anchorWidth + ScreenUtil.dp2px(6),  // X轴：锚点右侧
                anchorY// Y轴：与锚点顶部对齐
        );
    }
}
